import type { BodyFormat } from '../types';

// 格式化时间戳
export function formatTimestamp(timestamp: number): string {
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
}

// 格式化文件大小
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 格式化持续时间
export function formatDuration(ms: number): string {
  if (ms < 1000) {
    return `${ms}ms`;
  } else if (ms < 60000) {
    return `${(ms / 1000).toFixed(2)}s`;
  } else {
    const minutes = Math.floor(ms / 60000);
    const seconds = ((ms % 60000) / 1000).toFixed(2);
    return `${minutes}m ${seconds}s`;
  }
}

// 格式化HTTP状态码
export function formatStatusCode(code: number): { text: string; type: 'success' | 'warning' | 'error' | 'info' } {
  const text = `${code}`;
  
  if (code >= 200 && code < 300) {
    return { text, type: 'success' };
  } else if (code >= 300 && code < 400) {
    return { text, type: 'info' };
  } else if (code >= 400 && code < 500) {
    return { text, type: 'warning' };
  } else if (code >= 500) {
    return { text, type: 'error' };
  } else {
    return { text, type: 'info' };
  }
}

// 格式化请求体内容
export function formatBody(body: string, format: BodyFormat): string {
  if (!body) return '';

  try {
    switch (format) {
      case 'json':
        return JSON.stringify(JSON.parse(body), null, 2);
      
      case 'xml':
        // 简单的XML格式化
        return body.replace(/></g, '>\n<').replace(/^\s*\n/gm, '');
      
      case 'hex':
        return body
          .split('')
          .map(char => char.charCodeAt(0).toString(16).padStart(2, '0'))
          .join(' ')
          .toUpperCase();
      
      case 'javascript':
        // 简单的JavaScript格式化
        return body;
      
      case 'messagepack':
        // MessagePack格式（这里简化处理）
        return body;
      
      case 'text':
      default:
        return body;
    }
  } catch (error) {
    console.error('格式化内容失败:', error);
    return body;
  }
}

// 检测内容类型
export function detectContentType(headers: Record<string, string>): BodyFormat {
  const contentType = headers['content-type'] || '';
  
  if (contentType.includes('application/json')) {
    return 'json';
  } else if (contentType.includes('application/xml') || contentType.includes('text/xml')) {
    return 'xml';
  } else if (contentType.includes('application/javascript') || contentType.includes('text/javascript')) {
    return 'javascript';
  } else {
    return 'text';
  }
}

// 截断长文本
export function truncateText(text: string, maxLength: number = 100): string {
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
}

// 高亮搜索关键词
export function highlightText(text: string, keyword: string): string {
  if (!keyword) return text;
  
  const regex = new RegExp(`(${keyword})`, 'gi');
  return text.replace(regex, '<mark>$1</mark>');
}

// 解析URL
export function parseUrl(url: string) {
  try {
    const urlObj = new URL(url);
    return {
      protocol: urlObj.protocol,
      host: urlObj.host,
      pathname: urlObj.pathname,
      search: urlObj.search,
      hash: urlObj.hash,
      origin: urlObj.origin
    };
  } catch (error) {
    return {
      protocol: '',
      host: '',
      pathname: url,
      search: '',
      hash: '',
      origin: ''
    };
  }
}

// 获取HTTP方法的颜色
export function getMethodColor(method: string): string {
  const colors: Record<string, string> = {
    'GET': '#52c41a',
    'POST': '#1890ff',
    'PUT': '#fa8c16',
    'DELETE': '#ff4d4f',
    'PATCH': '#722ed1',
    'HEAD': '#13c2c2',
    'OPTIONS': '#eb2f96'
  };
  
  return colors[method.toUpperCase()] || '#666666';
} 